package top.goldenyear.porpoise.framework.common.model;

import top.goldenyear.porpoise.framework.common.enums.UserType;
import top.goldenyear.porpoise.framework.security.core.util.UserContext;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Data;
import cn.hutool.v7.core.map.MapUtil;

/**
 * 登录用户信息
 *
 * @author Airhead
 */
@Data
public class LoginUser implements Serializable {

  /** 用户编号 */
  private Integer id;

  private String userName;
  private String nickName;

  /**
   * 用户类型
   *
   * <p>关联 {@link UserType}
   */
  private Integer userType;

  /** 租户编号 */
  private Long tenantId;

  /** 授权范围 */
  private List<String> scopes;

  // ========== 上下文 ==========
  /**
   * 上下文字段，不进行持久化
   *
   * <p>1. 用于基于 LoginUser 维度的临时缓存
   */
  private Map<String, Object> context;

  public static LoginUser of() {
    LoginUser loginUser = new LoginUser();
    loginUser.setId(UserContext.getLoginUserId());
    loginUser.setUserName(UserContext.getLoginUserName());
    loginUser.setNickName(UserContext.getLoginUserName());
    return loginUser;
  }

  public void setContext(String key, Object value) {
    if (context == null) {
      context = new HashMap<>(1);
    }

    context.put(key, value);
  }

  public <T> T getContext(String key, Class<T> type) {
    return MapUtil.get(context, key, type);
  }
}
